<template>
 <div>
   <el-card class="box-card">
     <div slot="header" class="clearfix">
       <el-tag
         :key="tag.id"
         v-for="tag in dynamicTags"
         closable
         :effect="tag.id === selectid ? 'dark' : 'light'"
         :disable-transitions="false"
         @click="getOpListByType(tag)"
         @close="handleClose(tag)">
         {{tag.name}}
       </el-tag>
       <el-input
         class="input-new-tag"
         v-if="inputVisible"
         v-model="inputValue"
         ref="saveTagInput"
         size="small"
         @keyup.enter.native="handleInputConfirm"
         @blur="handleInputConfirm"
       >
       </el-input>
       <el-button v-else class="button-new-tag" size="small"  @click="addType">+ 类别</el-button>

       <el-button  style="float: right" @click="openDrawer">增加算子</el-button>

     </div>
     <div style="height: 500px; overflow: auto">
       <el-table
         :data="opdata"
         style="width: 100%">
         <el-table-column type="expand">
           <template slot-scope="props">
             <el-form label-position="left" inline class="demo-table-expand">

               <el-form-item label="算子内容">
                 <codemirror
                   v-model="props.row.content "
                   :options="cmOptions"
                 />
               </el-form-item>

             </el-form>
           </template>
         </el-table-column>
         <el-table-column
           label="算子名称"
           prop="name"
           width="200px"
         >
         </el-table-column>

         <el-table-column
           label="算子描述"
           prop="description">
         </el-table-column> <el-table-column
         label="更新时间"
         prop="update_datetime">
       </el-table-column>
         <el-table-column
           label="操作"
           fixed="right"
         >
           <template slot-scope="scope">
             <el-popconfirm
               title="确定删除吗？"
               @confirm="handleDel(scope)"
             >
               <el-button type="danger" slot="reference" size="mini" >删除</el-button>
             </el-popconfirm>
             <el-button size="mini" style="margin-left: 10px" @click="editimgType(scope)">编辑</el-button>
           </template>
         </el-table-column>
       </el-table>
     </div>


   </el-card>

   <el-drawer
     :modal="false"
     :wrapperClosable="false"
     :with-header="false"
     :visible.sync="dialogVisible"
     direction="ltr"
     size="80%"
     custom-class="demo-drawer"
     ref="drawer"
   >
     <el-card  style="background-color: #3c3f41; height: 100%;border: none;border-radius: 0;overflow: auto">
       <div style="float: right">
         <el-button style="background-color: black;border: none" @click="gptTest">chatGPT</el-button>
         <el-button style="background-color: black;border: none" @click="handleCloseDialog">取 消</el-button>
         <el-button style="background-color: black;border: none" @click="postParams2backEndtest">测 试</el-button>
         <el-button style="background-color: black;border: none" type="primary" @click="operatorPost2End">上 传</el-button>
       </div>
       <div style="margin-bottom: 50px">
         <span class="opfont">
         算子名称
       </span>
         <el-input style="width: 200px" v-model="postOperator.name" placeholder="请输入内容 "></el-input>
         <span class="opfont">
         算子描述
       </span>

         <el-input   style="width: 300px" v-model="postOperator.description" placeholder="请输入内容"></el-input>
       </div>
      <div style="margin-bottom: 20px">
        <span class="opfont">
         算子内容
       </span>
      </div>

       <codemirror
         v-model="postOperator.content"
         :options="cmOptions"
       />

       <div style="margin-bottom: 20px;margin-top: 20px">
            <span class="opfont">
               chatGPT的回答:
             </span>
       </div>

       <codemirror
         v-loading="loading"
         element-loading-text="正在获取chatGPT的回答"
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.8)"
         v-model="gptresponse"
         :options="cmOptions"
       />

       <div style="margin-bottom: 20px;margin-top: 20px">
            <span class="opfont">
               算子参数
             </span>
       </div>
       <codemirror
         v-model="strjsonparam"
         :options="cmOptions"
       />
       <div style="color: red;margin-top: 20px">
          <span style="color: red;display: block;margin-bottom: 20px" >
         错误提示:
       </span>
         <textarea ref="infotext" rows="10" cols="30" style="color: red;background-color:#3c3f41;border: none;width: 100% ">
          ：//
          </textarea>
       </div>

     </el-card>

   </el-drawer>

   <el-drawer
     :modal="false"
     :wrapperClosable="false"
     :with-header="false"
     :visible.sync="imgdialogVisible"
     direction="rtl"
     size="20%"
     custom-class="demo-drawer"
     ref="drawer"

   >
     <el-card  style="background-color: #3c3f41; height: 100%;border: none;border-radius: 0">
       <el-button style="background-color: black;border: none" @click="imgdialogVisible = false">取 消</el-button>
       <div style="margin-top: 80px">
         <el-card class="box-card">
           <div slot="header" class="clearfix">
             测试图片
           </div>
           <el-image :src="picUrl">
           </el-image>
         </el-card>
         <el-card class="box-card">
           <div slot="header" class="clearfix">
             测试结果
           </div>
           <el-image :src="resultPicUrl">
           </el-image>
         </el-card>
       </div>


     </el-card>

   </el-drawer>
 </div>
</template>

<script>
import * as api from './api'
import { GetOpList, OpPost2End, Post2End } from '@/views/basicoperator/optest/api'
import { AddObj, DelObj, DelOp, GetGPT } from './api'

import 'codemirror/theme/darcula.css'


export default {
  name: 'formSelect',

  data () {
    return {
      loading:false,
      gptresponse:`





      `,
      imgdialogVisible: false,
      selectid: 1,
      opname: '',
      dialogVisible: false,
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      opdata: [],
      cmOptions: {
        autorefresh: true,
        tabSize: 4,
        lineNumbers: true,
        mode: 'text/x-python',
        theme: 'darcula',
        line: true,
        viewportMargin: Infinity,
        highlightDifferences: true,
        autofocus: false,
        indentUnit: 2,
        smartIndent: true,
        showCursorWhenSelecting: true,
        firstLineNumber: 1
      },
      strjsonparam: `
{
   "ksizeA": 321,
   "ksizeB": 21,
   "sigmaX": 22,
   "sigmaY": 44
}`,
      postOperator: {
        description: '',
        is_deleted: false,
        name: '',
        content: `
# 按照以下格式编写算子，参数与算子的参数列表对应以json格式上传
def gauss(img,ksizeA,ksizeB, sigmaX, sigmaY):
    gauss_img = cv2.GaussianBlur(img, (ksizeA,ksizeB), sigmaX, sigmaY)
    return gauss_img
img = globals()['localimg']
strparams = locals()['params']
globals()['localimg'] = gauss(img,strparams.get('ksizeA'),strparams.get('ksizeB'),strparams.get('sigmaX'),strparams.get('sigmaY'))
# 算子参数
# {
#     "ksizeA": 321,
#     "ksizeB": 21,
#     "sigmaX": 22,
#     "sigmaY": 44
# }
     `,
        params: '',
        parameters: '',
        creator: 1,
        type: 1
      },
      resultPicUrl: 'http://127.0.0.1:8000/media/test/1.jpg',
      picUrl: 'http://127.0.0.1:8000/media/test/1.jpg'
    }
  },
  created () {
    this.pageRequest()
    this.getOpListByType(1)
  },
  methods: {
    async gptTest () {
      this.loading = true
      console.log(this.postOperator.content)
      const res = await GetGPT({
        a: this.postOperator.content
      })
      console.log(res)
      if(res.code === 2000){
        this.gptresponse = res.data.data
        this.loading = false
      }else{
        this.$message.error(res.msg)
      }


    },
    openDrawer () {
      this.imgdialogVisible = true
      const that = this
      setTimeout(() => {
        that.dialogVisible = true
      }, 300)
    },

    async postParams2backEndtest () {
      try {
        this.params = JSON.parse(this.strjsonparam)
      } catch (e) {
        this.$message.error(`${this.strjsonparam} 不是json格式！`)
      }
      this.fn = this.postOperator.content
      for (const i in this.params) {
        this.params[i] = parseInt(this.params[i])
      }
      const res = await Post2End({ params: this.params, fn: this.fn, url: '/media/test/1.jpg' })
      console.log(res)
      if (res.err === 4000) {
        this.$message.error('算子有错误！错误信息如下：' + res.msg)
        this.$refs.infotext.innerText = res.msg
      } else {
        this.resultPicUrl = 'data:image/jpg;base64,' + res.data.data
        this.$message.success('测试完成')
      }
    },

    async operatorPost2End () {
      this.dialogVisible = false
      try {
        this.postOperator.parameters = JSON.parse(this.strjsonparam)
      } catch (e) {
        this.$message.error(`${this.strjsonparam} 不是json格式！`)
      }
      this.postOperator.type = 4
      const res = await OpPost2End(this.postOperator)
      if (res.code === 2000) {
        this.$message.success(res.msg)
        this.getOpListByType({ id: this.selectid })
      } else {
        this.$message.error(res.msg)
      }
    },
    async handleDel (e) {
      const res = await DelOp(e.row.id)
      if (res.code === 2000) {
        this.$message.success(res.msg)

        this.getOpListByType({ id: this.selectid })
      } else {
        this.$message.error(res.msg)
      }
    },
    editimgType () {

    },
    handleCloseDialog () {
      this.dialogVisible = false
      this.imgdialogVisible = false
    },
    async getOpListByType (tag) {
      this.selectid = tag.id
      this.postOperator.type = tag.id
      const res = await api.GetOpList({
        typeid: tag.id
      })
      if (res.code === 2000) {
        // this.$message.success(res.msg)
        this.opdata = res.data.data
        console.log(tag)
      } else {
        this.$message.error(res.msg)
      }
    },
    // 获取算子类别
    async pageRequest (query) {
      const res = await api.GetList(query)
      this.dynamicTags = res.data.data
      console.log(this.dynamicTags)
    },
    addRequest (row) {
      console.log('api', api)
      return api.AddObj(row)
    },
    updateRequest (row) {
      console.log('----', row)
      return api.UpdateObj(row)
    },
    delRequest (row) {
      return api.DelObj(row.id)
    },

    async handleClose (tag) {
      const res = await DelObj(tag.id)
      if (res.code === 2000) {
        this.$message.success(res.msg)
        this.pageRequest()
      } else {
        this.$message.error(res.msg)
      }
    },
    async addType () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 上传算子类别
    async handleInputConfirm () {
      const res = await AddObj({
        name: this.inputValue
      })
      if (res.code === 2000) {
        this.pageRequest()
        this.$message.success(res.msg)
      } else {
        this.$message.error(msg)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>
<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.opfont{
  height: 20px;
  color: white;
  font-size: 20px;
}
</style>
